import { Directive, HostListener } from '@angular/core';
import { NgModel } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';

@Directive({
  selector: '[appCurrencyInputMask]',
  providers: [NgModel, CurrencyPipe],

})
export class MyDirective {

  constructor(private model: NgModel, private currencyPipe: CurrencyPipe) {
  }

  @HostListener('blur', ['$event'])
  onInputChange($event) {
    let value = $event.target.value;
    if (!value) {
      return;
    }

    let plainNumber: number;
    let formattedValue: string;


    let decimalSeparatorIndex = value.lastIndexOf('.');
    if (decimalSeparatorIndex > 0) {
      // if input has decimal part
      let wholeNumberPart = value.substring(0, decimalSeparatorIndex);
      let decimalPart = value.substr(decimalSeparatorIndex + 1);
      plainNumber = parseFloat(wholeNumberPart.replace(/[^\d]/g, '') + '.' + decimalPart);
    } else {
      // input does not have decimal part
      plainNumber = parseFloat(value.replace(/[^\d]/g, ''));
    }

    if (!plainNumber) {
      formattedValue = '';
    } else {
      formattedValue = this.currencyPipe.transform(plainNumber.toFixed(2), 'USD', true);
    }

    this.model.valueAccessor.writeValue(formattedValue);
  }
}
